const { pool } = require('./db');
const bcrypt = require('bcryptjs');

// 用户注册
async function registerUser(username, email, password) {
    try {
        // 检查用户名或邮箱是否已存在
        const [existingUsers] = await pool.execute('SELECT * FROM users WHERE username = ? OR email = ?', [username, email]);
        if (existingUsers.length > 0) {
            throw new Error('用户名或邮箱已被使用');
        }

        // 加密密码
        const hashedPassword = await bcrypt.hash(password, 10);

        // 插入新用户
        const [result] = await pool.execute('INSERT INTO users (username, email, password, role) VALUES (?,?,?,"user")', [username, email, hashedPassword]);
        return result.insertId;
    } catch (error) {
        throw error;
    }
}

// 用户登录
async function loginUser(username, password) {
    try {
        // 查询用户
        const [users] = await pool.execute('SELECT * FROM users WHERE username = ?', [username]);
        if (users.length === 0) {
            throw new Error('用户名或密码错误');
        }

        const user = users[0];
        // 验证密码
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            throw new Error('用户名或密码错误');
        }

        return user;
    } catch (error) {
        throw error;
    }
}

// 用户注销
async function logoutUser() {
    // 这里可以处理一些清理操作，例如清除会话或令牌
    return true;
}

// 验证用户权限
async function checkUserRole(userId, requiredRole) {
    try {
        const [users] = await pool.execute('SELECT role FROM users WHERE id = ?', [userId]);
        if (users.length === 0) {
            throw new Error('用户不存在');
        }

        const user = users[0];
        return user.role === requiredRole;
    } catch (error) {
        throw error;
    }
}

module.exports = {
    registerUser,
    loginUser,
    logoutUser,
    checkUserRole
};